import React, { useRef, useState } from 'react';
import { Alert, Snackbar, IconButton, Typography } from '@mui/material';
import { FileCopyOutlined as FileCopyIcon } from '@mui/icons-material';
import Tooltip from './Tooltip';

interface RulePathProps {
  text?: string;
  style?: React.CSSProperties;
  [key: string]: any;
}

const RulePath: React.FC<RulePathProps> = ({ text, style, ...others }) => {
  const textAreaRef = useRef<HTMLDivElement>(null);
  const [open, setOpen] = useState(false);

  const copyCodeToClipboard = (): void => {
    const el = textAreaRef.current;
    if (!el) return;

    if (window.getSelection) {
      const range = document.createRange();
      range.selectNode(el);

      const selection = window.getSelection();
      selection?.removeAllRanges();
      selection?.addRange(range);
    }
    document.execCommand('copy');
    clearSelection();
    setOpen(true);
  };

  const clearSelection = (): void => {
    if (window.getSelection) {
      window.getSelection()?.removeAllRanges();
    } else if ((document as any).selection) {
      (document as any).selection.empty();
    }
  };

  if (!text || text.includes('undefined')) {
    return null;
  }

  return (
    <div style={style} {...others}>
      <Typography
        variant="caption"
        ref={textAreaRef}
        sx={{
          color: (theme) => theme.palette.text.secondary,
          fontFamily: 'Menlo, Monaco, Consolas, "Courier New", monospace',
        }}
      >
        {text}
        <span>
          <Tooltip title="Copy" placement="top">
            <IconButton
              aria-label="copy"
              size="small"
              sx={{
                padding: 0,
                opacity: 0.7,
                fontSize: '1.2em',
                marginLeft: '0.3em',
              }}
              onClick={copyCodeToClipboard}
            >
              <FileCopyIcon fontSize="inherit" />
            </IconButton>
          </Tooltip>
        </span>
      </Typography>

      <Snackbar
        open={open}
        autoHideDuration={3000}
        onClose={() => setOpen(false)}
      >
        <Alert elevation={6} variant="filled" severity="success">
          Copied to clipboard
        </Alert>
      </Snackbar>
    </div>
  );
};

export default RulePath;

